<template>
  <div
    id="container"
    class="text-white text-sm bg-primary-300 min-h-screen pb-4"
  >
    <Header />
    <div id="main" class="bg-primary-300 p-6 text-black">
      <div class="rounded bg-white mx-4 my-4 py-6">
        <div class="px-6 flex justify-between items-center">
          <h1 class="text-lg font-semibold">我的作品</h1>
          <button
            @click="openCreateForm"
            class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
          >
            新建作品
          </button>
        </div>
      </div>
      <div class="rounded bg-white mx-4 mt-4 py-6">
        <div v-if="info && info.length > 0">
          <div
            id="book-list"
            class="p-2 grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4"
          >
            <div class="book" v-for="book in info" :key="book.id">
              <div class="relative">
                <a :href="'/book/' + book.id">
                  <img
                    :src="book.cover_image_url"
                    alt="封面加载失败"
                    class="rounded h-full w-full object-contain"
                    referrerPolicy="no-referrer"
                    v-if="book.cover_image_url"
                  />
                  <img
                    v-else
                    src="../assets/images/default_cover.jpg"
                    alt="默认封面"
                    class="rounded h-full w-full object-contain"
                  />
                  <div
                    class="rounded absolute text-white bottom-0 right-0 bg-blue-500 px-1 text-sm"
                  >
                    {{ book.category_name }}
                  </div>
                </a>
              </div>
              <div class="flex justify-between items-center mt-2">
                <div>
                  <p class="truncate">{{ book.name }}</p>
                  <p class="text-primary-200 text-sm">
                    作者: {{ book.user_name }}
                  </p>
                </div>
                <div class="flex gap-2">
                  <button
                    @click="openEditForm(book.id)"
                    class="text-blue-500 hover:text-blue-700 text-sm"
                  >
                    编辑
                  </button>
                  <button
                    @click="deleteBook(book.id)"
                    class="text-red-500 hover:text-red-700 text-sm"
                  >
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="text-center text-2xl p-8">暂无作品</div>
      </div>
    </div>
    <Footer />

    <!-- 悬浮表单弹窗 -->
    <BookForm
      v-model:visible="showForm"
      :is-edit="isEditMode"
      :book-id="currentBookId"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script>
import axios from "axios";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import BookForm from "@/components/BookForm.vue";
import showMessage from "@/utils/message.js";

export default {
  name: "Owned",
  components: { Header, Footer, BookForm },
  data() {
    return {
      info: null,
      showForm: false, // 控制弹窗显示
      isEditMode: false, // 标识编辑模式
      currentBookId: null, // 当前编辑的书籍ID
    };
  },
  mounted() {
    this.get_owned_books();
  },
  methods: {
    // 获取作品列表
    get_owned_books() {
      axios
        .get("/api/owned/", {
          headers: {
            Authorization: "JWT " + localStorage.getItem("token"),
          },
        })
        .then((response) => {
          this.info = response.data;
        })
        .catch((error) => {
          console.error("获取作品失败:", error);
        });
    },

    // 打开新建表单
    openCreateForm() {
      this.isEditMode = false;
      this.currentBookId = null;
      this.showForm = true;
    },

    // 打开编辑表单
    openEditForm(bookId) {
      this.isEditMode = true;
      this.currentBookId = bookId;
      this.showForm = true;
    },

    // 表单提交成功回调
    handleFormSuccess() {
      this.get_owned_books(); // 刷新列表
    },

    // 删除作品
    deleteBook(bookId) {
      if (!confirm("确定要永久删除该作品吗？")) return;
      axios
        .delete(`/api/book/${bookId}/`, {
          headers: { Authorization: "JWT " + localStorage.getItem("token") },
        })
        .then(() => {
          this.info = this.info.filter((book) => book.id !== bookId);
          showMessage("作品删除成功", "info");
        })
        .catch((error) => {
          console.error("删除失败:", error);
          showMessage("操作失败，请重试");
        });
    },
  },
};
</script>

<style scoped>
.book {
  padding: 0.5rem;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.book:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.cover {
  overflow: hidden;
}
</style>
